import sys
import os
import importlib.util

def run_plugin(plugin_path, plugin_name):
    try:
        if hasattr(sys, 'base_prefix') and sys.prefix != sys.base_prefix:
            base_dir = sys.base_prefix
            scripts_dir = os.path.join(base_dir, 'Scripts')
            dlls_dir = os.path.join(base_dir, 'DLLs')
            paths_to_add = [p for p in [base_dir, scripts_dir, dlls_dir] if os.path.exists(p)]
            current_path = os.environ.get('PATH', '')
            new_path = ';'.join(paths_to_add) + ';' + current_path
            os.environ['PATH'] = new_path

        os.environ['AIA_PLUGIN_NAME'] = plugin_name

        print(f"STATUS::插件 '{plugin_name}' 已启动。")
        sys.stdout.flush()

        module_name = f"plugin_module_{plugin_name.replace(' ', '_')}"

        spec = importlib.util.spec_from_file_location(module_name, plugin_path)
        if spec is None or spec.loader is None:
            raise RuntimeError(f"无法为插件 '{plugin_name}' 创建模块规范。")

        module = importlib.util.module_from_spec(spec)
        sys.modules[module_name] = module
        spec.loader.exec_module(module)

        if hasattr(module, 'run_plugin'):
            module.run_plugin()
        elif hasattr(module, 'main'):
            module.main()
        else:
            raise AttributeError("插件缺少入口函数 (run_plugin 或 main)")

        print(f"STATUS::插件 '{plugin_name}' 执行完毕或已退出。")
        sys.stdout.flush()

    except ImportError as e:
        missing_module = e.name if e.name else "一个未知的库"
        error_msg = f"""运行插件 '{plugin_name}' 失败！\n\n缺少依赖库: {missing_module}\n\n请在 "设置 -> Python环境" 中安装它。"""
        print(f"ERROR::{error_msg}")
        sys.stdout.flush()

    except Exception as e:
        import traceback
        detailed_error = traceback.format_exc()
        error_msg = f"运行插件 '{plugin_name}' 时出现未知错误: {e}\n\n{detailed_error}"
        print(f"ERROR::{error_msg}")
        sys.stdout.flush()

if __name__ == '__main__':
    if len(sys.argv) == 3:
        plugin_path_arg = sys.argv[1]
        plugin_name_arg = sys.argv[2]
        run_plugin(plugin_path_arg, plugin_name_arg)